package com.kmis.services.Impl;


import com.kmis.common.exception.BusinessException;
import com.kmis.vo.UserVo;
import com.kmis.web.ApiResult;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.If;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.util.SqlUtil;
import org.springframework.dao.DataAccessException;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import com.kmis.services.IUserService;
import com.kmis.entities.User;
import com.kmis.mappers.UserMapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;

import javax.annotation.Resource;

import java.util.List;
import java.util.Objects;

import static com.kmis.entities.table.DepartmentTableDef.DEPARTMENT;
import static com.kmis.entities.table.UserTableDef.USER;

/**
 * 服务层实现。
 *
 * @author MLB
 * @since 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper mapper;

    @Override
    public UserVo getByUserName(String username) {
        UserVo users = QueryChain.of(mapper)
                .from(USER)
                .select(USER.USERNAME,
                        DEPARTMENT.DEPARTMENT_NAME.as("depName"),
                        USER.PASSWORD,
                        USER.NICKNAME,
                        USER.PHONE,USER.EMAIL,
                        USER.AVATAR,
                        USER.SEX,
                        USER.STATUS)
                .leftJoin(DEPARTMENT).on(USER.DEP_ID.eq(DEPARTMENT.ID))
                .where(USER.USERNAME.eq(username))
                .oneAs(UserVo.class);
        return users;
    }

    @Override
    public ApiResult selectAllUsers() {
        List<UserVo> userList = QueryChain.of(mapper)
                .select(USER.DEFAULT_COLUMNS,
                        DEPARTMENT.DEPARTMENT_NAME.as("depName"),
                        DEPARTMENT.ID.as("depId"))
                .from(USER)
                .leftJoin(DEPARTMENT).on(USER.DEP_ID.eq(DEPARTMENT.ID))
                .listAs(UserVo.class);
        return ApiResult.ok("查询成功").put("userInfo", userList);
    }

    @Override
    public ApiResult insertUser(User user) throws DataAccessException {
        User insertUser = new User();
        String password = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt());
        insertUser.setUsername(user.getUsername());
        insertUser.setPassword(password);
        insertUser.setNickname(user.getNickname());
        insertUser.setEmail(user.getEmail());
        insertUser.setPhone(user.getPhone());
        insertUser.setDepId(user.getDepId());
        insertUser.setSex(user.getSex());
        insertUser.setRemark(user.getRemark());
        int row = mapper.insertSelective(insertUser);
        System.out.println(row);
        if (Objects.equals(row, 1)) {
            return ApiResult.ok("新增用户成功！");
        } else {
            return ApiResult.error(-1, "新增用户失败！");
        }
    }
    @Override
    public ApiResult removeUserById(Integer id) {
        try{
            QueryWrapper query = QueryWrapper.create()
                .from(USER)
                .where(USER.USER_ID.eq(id));
            boolean b = SqlUtil.toBool(getMapper().deleteByQuery(query));
            if (!b){
                return ApiResult.error(-1,"删除失败");
            }else{
                return ApiResult.ok("删除成功！");
            }
        }catch (RuntimeException e){
            throw new BusinessException(e.getMessage());
        }
    }

    @Override
    public ApiResult updateUser(User user) {
        try{
            QueryWrapper query = QueryWrapper.create()
                    .from(USER)
                    .where(USER.USER_ID.eq(user.getUserId()));

            int row = mapper.updateByQuery(user, query);
            if(row!=1){
                return ApiResult.error(-1,"更新失败！");
            }else{
                return ApiResult.ok("更新成功!");
            }
        }catch (RuntimeException e){
            throw new BusinessException(e.getMessage());
        }
    }

    @Override
    public ApiResult page(Integer pageNumber, Integer pageSize) {
            QueryWrapper query = QueryWrapper.create()
                .select(USER.DEFAULT_COLUMNS,
                        DEPARTMENT.DEPARTMENT_NAME.as("depName"),
                        DEPARTMENT.ID)
                .from(USER)
                .leftJoin(DEPARTMENT).on(USER.DEP_ID.eq(DEPARTMENT.ID));
        Page<UserVo> page = Page.of(pageNumber,pageSize);
        page = mapper.paginateAs(page,query,UserVo.class);
        return ApiResult.ok("查询成功").put("PageData",page);
    }

    @Override
    public ApiResult search(String nickname, String phone, String status,int pageNumber,int pageSize) {
        QueryWrapper query = QueryWrapper.create()
                .select(USER.DEFAULT_COLUMNS, DEPARTMENT.DEPARTMENT_NAME.as("depName"))
                .from(USER)
                .leftJoin(DEPARTMENT).on(USER.DEP_ID.eq(DEPARTMENT.ID))
                .where(USER.PHONE.eq(phone, If::hasText))
                .and(USER.NICKNAME.like(nickname, If::hasText))
                .and(USER.STATUS.eq(status, If::hasText));
        Page<UserVo> userVoPage = mapper.paginateAs(pageNumber, pageSize, query, UserVo.class);
        if(userVoPage.getTotalRow()!=0){
            return ApiResult.ok("查询成功").put("data",userVoPage);
        }else{
            return ApiResult.error("暂无数据");
        }

    }
}